package com.hopu.oa.controller.user;

import com.hopu.oa.dao.user.UserDao;
import com.hopu.oa.entity.mail.Mailreciver;
import com.hopu.oa.entity.menu.AoaSysMenu;
import com.hopu.oa.entity.notice.AoaNoticeList;
import com.hopu.oa.entity.task.AoaTasklist;
import com.hopu.oa.entity.user.AoaUser;
import com.hopu.oa.entity.user.AoaUserLoginRecord;
import com.hopu.oa.service.impl.mail.mailServiceImpl;
import com.hopu.oa.service.impl.menu.menuServiceImpl;
import com.hopu.oa.service.impl.notice.AoaNoticeListServiceImpl;
import com.hopu.oa.service.impl.task.TaskServiceImpl;
import com.hopu.oa.service.user.UserService;
import com.hopu.oa.until.MD5Util;
import com.hopu.oa.until.VerifyCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

/**
 * @ClassName: UserController
 * @Description: 登录
 * 权限 级联菜单
 * @Date: 2021/11/11 15:30
 */
@Controller
public class UserController {

    // 全局，验证码
    public String verifyCode = "";

    // 用户Service ->  DI
    @Autowired
    private UserService userService;

    // 主页 菜单 Service -> DI
    @Autowired
    private menuServiceImpl menuService;

    @Autowired
    private UserDao userDao;

    @Autowired
    private AoaNoticeListServiceImpl aoaNoticeListService;

    @Autowired
    private mailServiceImpl mailService;

    @Autowired
    private TaskServiceImpl taskService;

    @RequestMapping("/")
    public String tiao() {
        return "redirect:login";
    }

    @RequestMapping("/login")
    public String login(HttpServletRequest request) throws UnknownHostException {

        return "login/login";
    }


    /*
      @Description : 验证码, 更新
      @Date   :  2021/11/11
      @Param  :
      @return :
     */
    @RequestMapping("user_captcha")
    public void user_captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        VerifyCode vc = new VerifyCode();
        BufferedImage image = vc.getImage();

        //验证码
        verifyCode = vc.getText();

        System.out.println(vc.getText());

        //响应到前台src
        VerifyCode.output(image, response.getOutputStream());
    }


    /*
      @Description : 用户登录，表单提交
      @Date   :  2021/11/11
      @Param  : [userName, password, code]  【用户名/电话，密码，验证码】
      @return : java.lang.String
     */
    @RequestMapping("user_login")
    public String user_login(@RequestParam(value = "userName", required = false) String userName,
                             @RequestParam(value = "password", required = false) String password,
                             @RequestParam(value = "code", required = false) String code,
                             HttpSession session, Model model, HttpServletRequest request) throws Exception {


        /**
         * 登录密码加密
         */
        String md5Encode = MD5Util.md5Encode(password);


        AoaUser loginUser = (AoaUser) session.getAttribute("user");
        if (loginUser == null) {

             /*
            验证码比对，true往下走，false  ---> login.yml
            */
            if (code != null) // 一直报空指针，加个判断
            {
                if (!code.equals(verifyCode)) {
                    //数据回显
                    model.addAttribute("echoUserName", userName);
                    model.addAttribute("echoPassword", password);

                    //错误提示
                    model.addAttribute("errormess", "验证码错误");
                    return "login/login";
                }
            }

        }

        //查询用户
        //AoaUser aoaUser = userService.queryUserByNameOrTelAndPassword(userName, password);
/**
 * 根据加密后的密码，进行查询比对
 */
        AoaUser aoaUser = userService.queryUserByNameOrTelAndPassword(userName, md5Encode);




        /*
            用户不为空，登录成功.   ---> index.yml
            一二级菜单 -> request
         */
        if (aoaUser != null) {
            /*
              右侧导航栏 ，一二级菜单
            */
            List<AoaSysMenu> oneMenuAll = menuService.selectByOne(aoaUser.getRoleId());
            List<AoaSysMenu> twoMenuAll = menuService.selectByTwo(aoaUser.getRoleId());

            //一，二级菜单  -> Request
            model.addAttribute("oneMenuAll", oneMenuAll);
            model.addAttribute("twoMenuAll", twoMenuAll);


            //  用户 -> Request
            model.addAttribute("user", aoaUser);

            //  用户 -> Session
            session.setAttribute("user", aoaUser);

            //获取当前时间
            Date date = new Date();
            //转换格式 使用format将这个日期转换成我们需要的格式
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            System.out.println(formatter.format(date));
            //获取当前IP地址
            InetAddress address = InetAddress.getLocalHost();
            System.out.println(address);
            //获取浏览器信息
            String ua = request.getHeader("User-Agent");
            System.out.println("ua = " + ua);
            AoaUserLoginRecord aoaUserLoginRecord = new AoaUserLoginRecord();
            aoaUserLoginRecord.setBrowser(ua);
            aoaUserLoginRecord.setIpAddr(address.toString());
            aoaUserLoginRecord.setLoginTime(formatter.format(date));
            aoaUserLoginRecord.setUserId(aoaUser.getUserId());
            System.out.println(aoaUserLoginRecord);
            int i = userDao.insertLoginRecord(aoaUserLoginRecord);
            System.out.println("i = " + i);
            return "redirect:index";
        } else   // 未查询到用户 ：用户名/密码 为空   ---> login.yml
        {
            //数据回显
            model.addAttribute("echoUserName", userName);
            model.addAttribute("echoPassword", password);

            //错误提示
            model.addAttribute("errormess", "用户名或密码错误");
            return "login/login";
        }

    }

    @RequestMapping("menucha")
    public String menucha(Model model, String find, HttpSession session) {
        AoaUser user = (AoaUser) session.getAttribute("user");
        List<AoaSysMenu> aoaSysMenus = menuService.selectByAllMenu(find, user.getRoleId());
        List<AoaSysMenu> twoMenuAll = menuService.selectByTwo(user.getRoleId());
        List<AoaSysMenu> oneMenuAll = new ArrayList<>();
        List<AoaSysMenu> aoaSysMenusOneNew = new ArrayList<>();
        for (int i = 0; i < aoaSysMenus.size(); i++) {

            if (aoaSysMenus.get(i).getParentId() == 0) {
                oneMenuAll.add(aoaSysMenus.get(i));
            } else {
                AoaSysMenu aoaSysMenusOne = menuService.selectOneByTwo(aoaSysMenus.get(i).getParentId(), user.getRoleId());
                aoaSysMenusOneNew.add(aoaSysMenusOne);
                for (int i1 = 0; i1 < aoaSysMenusOneNew.size() - 1; i1++) {
                    if (!oneMenuAll.contains(aoaSysMenusOneNew.get(i1))) {
                        oneMenuAll.add(aoaSysMenusOneNew.get(i1));
                    }
                }
            }
        }
        HashSet h = new HashSet(oneMenuAll);
        oneMenuAll.clear();
        oneMenuAll.addAll(h);
        for (AoaSysMenu aoaSysMenu : oneMenuAll) {
            System.out.println(aoaSysMenu);
        }
        //一，二级菜单  -> Request
        model.addAttribute("oneMenuAll", oneMenuAll);
        model.addAttribute("twoMenuAll", twoMenuAll);
        return "common/leftlists";
    }


    /**
      @Description : 退出
      @Date   :  2021/11/12
      @Param  : [model]
      @return : java.lang.String
     */
    @RequestMapping("loginout")
    public String loginOut(Model model, HttpSession session) {
        session.removeAttribute("user");
        return "login/login";
    }

    @RequestMapping("/index")
    public String index(HttpSession session, Model model) {
        if (session.getAttribute("user") != null) {
            AoaUser aoaUser = (AoaUser) session.getAttribute("user");
            List<AoaSysMenu> oneMenuAll = menuService.selectByOne(aoaUser.getRoleId());
            List<AoaSysMenu> twoMenuAll = menuService.selectByTwo(aoaUser.getRoleId());

            //一，二级菜单  -> Request
            model.addAttribute("oneMenuAll", oneMenuAll);
            model.addAttribute("twoMenuAll", twoMenuAll);

            //  用户 -> Request
            model.addAttribute("user", aoaUser);
            session.setAttribute("user", aoaUser);

            List<Mailreciver> noreadlist = mailService.findByReadAndDelAndReciverId(0, 0, aoaUser.getUserId());
            model.addAttribute("mail", noreadlist.size());
            System.out.println("noreadlist = " + noreadlist.size());
            List<AoaNoticeList> aoaNoticeLists = aoaNoticeListService.queryNoticeListById(aoaUser.getUserId(), null, 0, 0);
            model.addAttribute("notice", aoaNoticeLists.size());
            System.out.println("aoaNoticeLists.size() = " + aoaNoticeLists.size());
            List<AoaTasklist> allTask = taskService.findAllTask(aoaUser.getUserId(), null, 0, 0, null);
            model.addAttribute("task", allTask.size());
            System.out.println("allTask = " + allTask.size());
            return "index/index";
        } else {
            return "login";
        }
    }


}